#include "light.h"
#include "sceneobj.h"
#include "scenemanager.h"
#include "meshmanager.h"
#include "mesh.h"
#include <stdio.h>

namespace ZH
{
	Light::Light(const std::string& name)
		: SceneNode(name),
		m_bEnable(true),
		m_pDebug(NULL),
		m_bShowDebug(false)
	{
		memset(&m_Light, 0, sizeof(D3DLIGHT9));
		D3DXCOLOR white(1.0f, 1.0f, 1.0f, 1.0f);
		D3DXVECTOR3 position(10.0f, 10.0f, 10.0f);
		D3DXVECTOR3 direction(-1.0f, -1.0f, -1.0f);
		D3DXVec3Normalize(&direction, &direction);
		m_Light.Type		= D3DLIGHT_DIRECTIONAL;
		m_Light.Ambient   = white * 0.4f;
		m_Light.Diffuse   = white;
		m_Light.Specular  = white * 0.6f;
		m_Light.Position  = position;
		m_Light.Direction = direction;
		m_Light.Range        = 1000.0f;
		m_Light.Falloff      = 1.0f;
		m_Light.Attenuation0 = 1.0f;
		m_Light.Attenuation1 = 0.0f;
		m_Light.Attenuation2 = 0.0f;
		m_Light.Theta        = 0.5f;
		m_Light.Phi          = 0.7f;
	}

	Light::~Light()
	{
		if (m_pDebug)
		{
			SceneManager::getSingleton().DestroySceneNode(m_pDebug);
		}
	}

	void Light::ShowDebug(bool Show)
	{
		if (Show && NULL == m_pDebug)
		{
			m_pDebug = SceneManager::getSingleton().CreateSceneNode();
			SceneObj* pObj = SceneManager::getSingleton().CreateSceneObj("", "Arrow");
			RenderPass* pass = pObj->GetPass();
			pass->ambient_color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
			pass->material.Ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);;
			pass->depth_write = false;
			pass->cast_shadow = false;
			pass->recive_shadow = false;
			pass->light_enable = false;
			m_pDebug->AddSceneObj(pObj);
			//AddChildNode(m_pDebug);
		}

		if (false == Show && m_pDebug)
		{
			//RemoveChildNode(m_pDebug);
		}
		m_bShowDebug = Show;
	}

	D3DXVECTOR3 Light::GetDirection()
	{
		if (m_bPosDirty)
			_UpdatePosInfo();

		return m_Light.Direction;
	}

	void Light::_UpdatePosInfo()
	{
		SceneNode::_UpdatePosInfo();
		m_Light.Position = GetDrivePosition();
		m_Light.Direction = m_Orientation.zAxis();
	}

	void Light::SetDirection(const slm::vec3& direction)
	{
		slm::vec3 dir(direction);
		dir.normalize();
		m_Orientation.fromToRotation(m_Position, m_Position - dir * 1.0f);
		_NotiyPosInfoDirty();
	}
}	// end of namespace ZH
